package com.ygqh.baby.controller.mobile;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.FileType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.model.YgChannelUserModel;
import com.ygqh.baby.po.YgChannel;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgChannelService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.HttpUtil;
import com.ygqh.baby.utils.ImageUtils;
import com.ygqh.baby.utils.QRCodeUtil;
import com.ygqh.baby.utils.SessionUtil;

/**
 * 渠道相关
 *
 * @author guohao
 */
@Controller
@RequestMapping("/mobile/channel")
public class YgChannelController {

	@Autowired
	private YgChannelService ygChannelService;
	@Autowired
	private DocumentConstant documentConstant;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private FileService fileService;
	@Value("${image.domain}")
	private String domain;
	@Autowired
	private RedisDao redisDao;

	/**
	 * 获取渠道下的员工列表
	 *
	 * @param channelId
	 *            主渠道id
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "findChannelUserList", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject findChannelEmployees(Long channelId, String callback) {
		JSONPObject json = null;
		List<YgChannel> list = ygChannelService.findByParentId(channelId);
		List<YgChannelUserModel> userList = new ArrayList<YgChannelUserModel>();
		int amount = 0;
		if (list != null) {
			for (YgChannel channel : list) {
				YgChannelUserModel model = new YgChannelUserModel();
				model.setUserName(channel.getLinkMan());
				model.setSourceCode(channel.getSourceCode());
				model.setCreateTime(channel.getCreateTime());
				userList.add(model);
			}
			amount = list.size();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("amount", amount);
		map.put("userList", userList);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	/**
	 * 添加渠道员工
	 *
	 * @param channelId
	 *            渠道id
	 * @param name
	 *            员工姓名
	 * @param telPhone
	 *            联系电话
	 * @param callback
	 * @return
	 */
	@RequestMapping(value = "addChannelUser", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject addChannelUser(@RequestParam(required = true) Long channelId, @RequestParam(required = true) String name,
			@RequestParam(required = true) String telPhone, String callback) {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		YgChannel channel = ygChannelService.findById(channelId);
		if (channel.getParentId().intValue() > 0 || !channel.getSourceCode().equals(user.getUserName())) {
			return new JSONPObject(callback, Message.error("渠道id有误", null));
		}
		channel.setParentId(channel.getId());
		channel.setLinkMan(name);
		channel.setTelPhone(telPhone);
		ygChannelService.save(channel);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, null));
		return json;
	}

	@RequestMapping("getQrcodeUrl")
	@ResponseBody
	public JSONPObject getQrcodeUrl(String callback) throws WeixinException {
		JSONPObject json = null;
		YgUser user = SessionUtil.getCurrentUser();
		String codeUrl = wxMpAuthorityService.findQrCodeUrl(user.getSourceCode());
		Map<String, String> map = new HashMap<String, String>();
		map.put("codeUrl", codeUrl);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}

	@RequestMapping("isMainUser")
	@ResponseBody
	public JSONPObject isMainUser(String callback) throws WeixinException {
		YgUser user = SessionUtil.getCurrentUser();
		Map<String, Object> map = new HashMap<String, Object>();
		YgChannel channel = ygChannelService.findByCode(user.getSourceCode());
		if (channel.getParentId().intValue() == 0) {
			map.put("isMain", true);
		} else {
			map.put("isMain", false);
		}
		map.put("shortName", channel.getShortName());
		map.put("channelId", channel.getId());
		map.put("sourceCode", channel.getSourceCode());
		return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
	}

	@RequestMapping("getShareQrcodeUrl")
	@ResponseBody
	public JSONPObject getQrcodeUrl(String shareUrl,String mainImageUrl,Long productId,String productName, String callback, HttpServletRequest request) throws WeixinException {
		
		JSONPObject json = null;
		String qrCodeUrl = "";
		String shortUrl = "";
		productName=productName.replace("【预售】", "");
		try {
			qrCodeUrl = QRCodeUtil.getQrCodeUrl(shareUrl, "channelShare", request);
			String ext =".jpg";
			String path = request.getRealPath("/");
			String targetPath = path + "/ShareProductImage/second_"+productId+ext;		
			String firstPath = path + "/ShareProductImage/first_"+productId+ext;
			String temptPath = path + "/ShareProductImage/";
			String textPath = path + "/ShareProductImage/text_"+productId+ext;
			//将图片下载到本地
			String yunTupian = HttpUtil.saveImageToDisk(domain + "/default/img0_layer.jpg", targetPath);
			temptPath=HttpUtil.saveImageToDisk(mainImageUrl, temptPath);
			
			if (!StringUtil.isBlank(qrCodeUrl)) {
				
				//将商品主图合并到分享图中
				ImageUtils.pressImageMark2(temptPath, yunTupian, firstPath, 10, 10, 1.0f,0,0);
				//将二维码合并到已经合成后的商品图
				
				ImageUtils.pressImageMark(qrCodeUrl, firstPath, qrCodeUrl, 0, 0, 1.0f);
				//将产品名称加到图片
				ImageUtils.pressText(productName,qrCodeUrl, textPath,"Serif",20, Color.black,30,140, 840, 1.0f);
				File file = new File(textPath);
				
				
				qrCodeUrl = fileService.uploadImage(file, new FileType[] { FileType.QrCode }, ext, true, request);
				shortUrl = wxMpAuthorityService.getShortUrl(shareUrl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("codeUrl", qrCodeUrl);
		map.put("shortUrl", shortUrl);
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}
	@RequestMapping("getUserQrcodeUrl")
	@ResponseBody
	public JSONPObject getUserQrcodeUrl(String callback, HttpServletRequest request) throws WeixinException {
		
		JSONPObject json = null;
		String qrCodeUrl = "";
		String shortUrl = "";
		Map<String, String> map = new HashMap<String, String>();
		YgUser user = SessionUtil.getCurrentUser();
		qrCodeUrl=redisDao.get("zhanhui_"+user.getId());
		if(qrCodeUrl!=null){
			map.put("codeUrl", qrCodeUrl);
			return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		}
		
		try {
		
			qrCodeUrl =wxMpAuthorityService.findQrCodeUrl(user.getUserName());
			String ext =".jpg";
			String path = request.getRealPath("/");
			String targetPath = path + "/ShareProductImage/second_"+user.getId()+ext;		
			String firstPath = path + "/ShareProductImage/first_"+user.getId()+ext;
			String temptPath = path + "/ShareProductImage/"+user.getId()+ext;	
			String qrCodePath  = path + "/ShareProductImage/qrcode_"+user.getId()+ext;
			qrCodeUrl=HttpUtil.saveImageToTargetDisk(qrCodeUrl, qrCodePath);
			//将图片下载到本地
			String yunTupian = HttpUtil.saveImageToTargetDisk(domain + "default/default_layer.jpg", targetPath);
			
			if(user.getHeadImageUrl()==null){
				user=ygUserService.findById(user.getId());				
			}
			
			temptPath=HttpUtil.saveImageToTargetDisk(user.getHeadImageUrl(), temptPath);
			
			if (!StringUtil.isBlank(qrCodeUrl)) {
				
				//将个人头像合并到图片
				ImageUtils.pressImageMark2(temptPath, yunTupian, firstPath, 27, 809, 1.0f,144,144);
				//将二维码合并到已经合成后的商品图
				
				ImageUtils.pressImageMark2(qrCodeUrl, firstPath, qrCodeUrl, 212, 809, 1.0f,150,150);
				
				File file = new File(qrCodeUrl);
				
				
				qrCodeUrl = fileService.uploadImage(file, new FileType[] { FileType.QrCode }, ext, true, request);
				redisDao.set("zhanhui_"+user.getId(), qrCodeUrl, 3600000*24*3);
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		map.put("codeUrl", qrCodeUrl);
	
		json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, map));
		return json;
	}
}
